package com.erp.controller;

import com.erp.service.UserService;
import com.erp.utils.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author tj
 * @Date 2022-04-20 15:56:07
 */
public class LoginServlet extends HttpServlet {
    UserService userService = new UserService();
    ExceptionUtil exceptionUtil = new ExceptionUtil();
    Logger logger = LoggerFactory.getLogger(LoginServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;chartset=UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String verify = req.getParameter("verify");
        try {
            String getVerify = String.valueOf(req.getSession().getAttribute("codes"));
            if (!verify.equals(getVerify)) {
                throw new Exception("验证码错误！");
            }
            userService.login(username, password,req);

//            resp.getWriter().println("登录成功！");
            // 跳转到首页
            req.setAttribute("user",req.getSession().getAttribute("user"));
            resp.sendRedirect(req.getContextPath() + "/");
        } catch (Exception e) {

//            resp.getWriter().println(e.getMessage());
//            1.定义错误信息
//            2.包括错误信息的内容，返回上一级的路由
//            3.把这个包含错误信息的实体类传递到统一的错误信息的页面
//            ErrorMsg errorMsg = new ErrorMsg();
//            errorMsg.setMessage(e.getMessage());
//            errorMsg.setReturnPage("login.jsp");
//            // 设置错误信息
//            req.setAttribute("error",errorMsg);
//            // 请求转发
//            this.getServletContext().getRequestDispatcher("/error.jsp").forward(req,resp);
            // 统一封装的工具类
            exceptionUtil.error(e.getMessage(), "login.jsp", this.getServletContext(), req, resp);
        }

    }
}